package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.mongo.UserLocation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //保存或者更新地理位置信息
    public void updateLocation(Long userId, Double longitude, Double latitude, String addrStr) {
        //1、根据userId查询地理位置数据
        Query query = Query.query(Criteria.where("userId").is(userId));
        if(!mongoTemplate.exists(query, UserLocation.class)) {
            //2、不存在，保存
            UserLocation location = new UserLocation();
            location.setUserId(userId);
            location.setAddress(addrStr);
            location.setCreated(System.currentTimeMillis());
            location.setUpdated(System.currentTimeMillis());
            location.setLastUpdated(System.currentTimeMillis());
            GeoJsonPoint point = new GeoJsonPoint(longitude,latitude);
            location.setLocation(point);
            mongoTemplate.save(location);
        }else {
            //3、存在，更新   update user set name=1234 where
            Update update = Update.update("location", new GeoJsonPoint(longitude, latitude))
                    .set("address", addrStr);
            mongoTemplate.updateFirst(query,update,UserLocation.class);
        }
    }

    //搜附近
    public List<Long> findByUserId(Long userId, Long distance) {
        //1、查询当前用户的地理位置
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        UserLocation location = mongoTemplate.findOne(query, UserLocation.class);
        //2、绘制半径
        Distance dis = new Distance(distance/1000, Metrics.KILOMETERS);
        //3、绘制圆
        Circle circle = new Circle(location.getLocation(),dis);
        //4、地理位置检索
        Criteria criteria1 = Criteria.where("location").withinSphere(circle);
        Query query1 = Query.query(criteria1);
        List<UserLocation> list = mongoTemplate.find(query1, UserLocation.class);
        //获取id
        return CollUtil.getFieldValues(list, "userId", Long.class);
    }
}
